package cn.woniu.util;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class loginSuccessHandler implements AuthenticationSuccessHandler {


    @Autowired
    private RedisTemplate<String,String> redisTemplate;



    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //获取登录成功的用户信息
        String jwt = null;
        try {
            User user = (User) authentication.getPrincipal();
            jwt = JWTUtil.createJWT(user.getUsername());
            //TimeUnit.SECONDS:秒
            //TimeUnit.MINUTES:分钟
            redisTemplate.opsForValue().set("jwt:" + user.getUsername(), jwt,30, TimeUnit.MINUTES);
            System.out.println(user.getUsername());
            //设置字符集
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
//        String success = JSON.toJSONString(ResponseResult.SECCUSS);
            String success = JSON.toJSONString(new ResponseResult<>().ok(jwt));
            out.print(success);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
